from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel, Field, field_validator
from typing import List, Optional
from decimal import Decimal
from datetime import datetime
from tortoise.exceptions import DoesNotExist
from models.cart import Cart  # 导入模型

router = APIRouter(prefix="/cart", tags=["购物车"])

# -------------------------- 数据模型 --------------------------
# 输入模型（前端传入的数据）
class ShopcarIn(BaseModel):
    user_id: int = Field(description="用户ID(固定为1)")
    product_id: int = Field(description="商品ID")
    product_name: str = Field(description="商品名称")
    specs: str = Field(description="商品规格")
    toppings: str = Field(description="选中的小料")
    quantity: int = Field(description="商品数量")
    price: str = Field(description="前端传入的价格字符串（如'10.99'）")
    image_url: str = Field(description="图片链接")

    class Config:
        from_attributes = True

    # 转换价格为Decimal（存入数据库前）
    def convert_to_decimal(self):
        self.price = Decimal(self.price)
        return self

# 输出模型（后端返回给前端的数据）
class ShopcarOut(ShopcarIn):
    id: int = Field(description="购物车记录ID")
    price: Decimal = Field(description="价格（Decimal类型，需序列化为字符串）")
    add_time: datetime = Field(description="加入时间（datetime类型，需序列化为字符串）")
    update_time: datetime = Field(description="更新时间（datetime类型，需序列化为字符串）")

    class Config:
        from_attributes = True

    # 序列化：Decimal转字符串
    @field_validator('price', mode='after')
    def serialize_decimal(cls, value: Decimal):
        return str(value)

    # 序列化：datetime转ISO字符串
    @field_validator('add_time', 'update_time', mode='after')
    def serialize_datetime(cls, value: datetime):
        return value.isoformat()

# 更新数量请求体模型
class UpdateQuantityIn(BaseModel):
    quantity: int = Field(..., ge=1, description="商品数量（至少为1）")

# 删除/更新响应模型
class OperationResponse(BaseModel):
    message: str = Field(description="操作结果描述")
    success: bool = Field(description="操作是否成功")

# -------------------------- 核心接口 --------------------------
# 1. 加入购物车
@router.post("/add", response_model=ShopcarOut)
async def add_to_shopcar(item: ShopcarIn):
    try:
        item.convert_to_decimal()
        # 查找相同商品（未被物理删除的）
        existing_item = await Cart.get_or_none(
            user_id=item.user_id,
            product_id=item.product_id,
            specs=item.specs,
            toppings=item.toppings
        )

        if existing_item:
            # 存在则更新数量
            existing_item.quantity += item.quantity
            existing_item.update_time = datetime.now()  # 手动更新时间
            await existing_item.save()
            return existing_item
        else:
            # 不存在则创建新记录
            new_item = await Cart.create(
                **item.dict(),
                add_time=datetime.now(),
                update_time=datetime.now()
            )
            return new_item
    except Exception as e:
        import traceback
        print(traceback.format_exc())
        raise HTTPException(status_code=400, detail=str(e))

# 2. 获取购物车列表
@router.get("/list", response_model=List[ShopcarOut])
async def get_cart_list():
    try:
        # 直接查询所有未被物理删除的商品
        items = await Cart.filter(user_id=1).order_by("-update_time").all()
        return items
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

# 3. 删除购物车商品（物理删除，从数据库中彻底移除）
@router.delete("/item/{item_id}", response_model=OperationResponse)
async def delete_cart_item(item_id: int):
    try:
        # 只允许删除用户1的商品
        item = await Cart.get(id=item_id, user_id=1)
        # 执行物理删除（彻底从数据库删除）
        await item.delete()
        return {"message": "商品已从购物车彻底删除", "success": True}
    except DoesNotExist:
        raise HTTPException(status_code=404, detail="商品不存在或已删除")
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

# 4. 更新商品数量
@router.patch("/item/{item_id}/quantity", response_model=ShopcarOut)
async def update_cart_quantity(
    item_id: int,
    body: UpdateQuantityIn
):
    try:
        # 只允许更新用户1的商品
        item = await Cart.get(id=item_id, user_id=1)
        item.quantity = body.quantity  # 更新数量
        item.update_time = datetime.now()  # 更新时间
        await item.save()
        return item
    except DoesNotExist:
        raise HTTPException(status_code=404, detail="商品不存在或已删除")
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))